package top.hkyzf.study.j2se.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 *
 * java内置的4大核心函数式接口
 * 消费型接口 Consumer<T>    void accept(T t)
 * 供给型接口 Supplier<T>    T get()
 * 函数型接口 Function<T,R>  R apply(T t)
 * 断定型接口 Predicate<T>   booLean test(T t)
 *
 * @author 朱峰
 * @date 2021-8-11 10:45
 */
public class LambdaTest2 {
    @Test
    public void test1 () {
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累了，去天上人间买了瓶矿泉水，价格为：" + aDouble);
            }
        });

        System.out.println("*************************");

        happyTime(400, (aDouble) -> System.out.println("学习太累了，去天上人间喝了口水，价格为：" + aDouble));
    }
    private void happyTime(double money, Consumer<Double> com) {
        com.accept(money);
    }

    @Test
    public void test2 () {
        List<String> list = Arrays.asList("北京", "南京", "天津", "东京", "西京", "普京");

        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterStrs);

        List<String> filterList = filterString(list, s -> s.contains("京"));
        System.out.println(filterList);
    }
    // 按照指定的 Predicate 规则过滤
    private List<String> filterString(List<String> list, Predicate<String> pre) {
        List<String> filterString = new ArrayList<>();

        for (String str : list) {
            if(pre.test(str)) {
                filterString.add(str);
            }
        }

        return filterString;
    }
}
